package cn.edu.zjicm.wordsnet_d.activity;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import java.util.zip.ZipException;

import android.os.Process;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import cn.edu.zjicm.wordsnet_d.R;
import cn.edu.zjicm.wordsnet_d.data.DataManager;
import cn.edu.zjicm.wordsnet_d.data.MobclickAgentData;
import cn.edu.zjicm.wordsnet_d.data.StaticData;
import cn.edu.zjicm.wordsnet_d.datapersistent.AppPreference;
import cn.edu.zjicm.wordsnet_d.datapersistent.FileManager;
import cn.edu.zjicm.wordsnet_d.db.LocationAndSchoolFactory;
import cn.edu.zjicm.wordsnet_d.db.WordFactory;
import cn.edu.zjicm.wordsnet_d.download.UpdateManager;
import cn.edu.zjicm.wordsnet_d.lock.LockService;
import cn.edu.zjicm.wordsnet_d.synchronize.UserInterface;
import cn.edu.zjicm.wordsnet_d.util.BitmapUtil;
import cn.edu.zjicm.wordsnet_d.util.DateTimeUtils;
import cn.edu.zjicm.wordsnet_d.util.LogUtil;
import cn.edu.zjicm.wordsnet_d.util.Utils;

import com.umeng.analytics.MobclickAgent;
import com.xiaomi.mipush.sdk.MiPushClient;

public class WelcomeActivity extends Activity {
	private final int MIN_SHOW_TIME = 2000;
	private final String dynamicImageURL1 = "http://www.iwordnet.com/mobile/image/";
	private final int SET_ADS = 100;
	private final int GET_AD_FAILED = 101;// 获取图片失败
	private boolean hasSetAd = false;

	Handler mHandler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case SET_ADS:
				Bitmap bt = (Bitmap) msg.obj;
				setADs(bt);
				break;
			case GET_AD_FAILED:
				getImages();
				break;

			}
		};
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 全屏
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_welcome);
		if (shouldInitMiPush()) {
			MiPushClient.registerPush(WelcomeActivity.this, getResources().getString(R.string.mi_push_id), getResources().getString(R.string.mi_push_key));

		}
		// String regId = MiPushClient.getRegId(getApplicationContext());
		// LogUtil.d("Tag","regId="+regId);

		InitTask initTask = new InitTask();
		initTask.execute();

	}

	private boolean shouldInitMiPush() {
		ActivityManager am = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE));
		List<RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
		String mainProcessName = getPackageName();
		int myPid = Process.myPid();
		for (RunningAppProcessInfo info : processInfos) {
			if (info.pid == myPid && mainProcessName.equals(info.processName)) {
				return true;
			}
		}
		return false;
	}

	private class InitTask extends AsyncTask<Object, String, Boolean> {
		@Override
		protected Boolean doInBackground(Object... params) {
			boolean result = false;
			long delay = MIN_SHOW_TIME - doSomething();
			if (delay > 0) {
				try {
					Thread.sleep(delay);
					Log.e("slepp", delay + "");
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

			// 如果是新用户、或者已安装知米听力，不显示推荐知米听力的弹窗
			if (AppPreference.hasStudyingBook(WelcomeActivity.this) || UpdateManager.isZhimiListenInstalled(WelcomeActivity.this))
				AppPreference.setShowRecommendZhimiListen(WelcomeActivity.this, true);

			if (AppPreference.isFirstGuidePage(WelcomeActivity.this)) {
				GuideActivityFull.startActivity(WelcomeActivity.this);
			} else {
				if (AppPreference.getLoginID(WelcomeActivity.this) == "") {
					LoginActivity.startActivity(WelcomeActivity.this, true);
				} else if (!AppPreference.hasStudyingBook(WelcomeActivity.this)) { // 如果是新用户进入选择学习计划页面
					SelectBookActivity.mStartActivity(WelcomeActivity.this, StaticData.MODE_INIT);
				} else {
					MainActivity.startActivity(WelcomeActivity.this);
					LogUtil.d("进入MainActivity");
				}
			}
			if (!AppPreference.isHasFixedWordsLogTable(WelcomeActivity.this)) {
				new Thread(new Runnable() {
					@Override
					public void run() {
						AppPreference.setHasFixedWordsLogTable(WelcomeActivity.this, true);
						WordFactory.getInstance(WelcomeActivity.this).fixDB();
					}
				}).start();
			}
			finish();
			return result;
		}
	}

	private long doSomething() {
		long start = System.currentTimeMillis();

		splitBook();

		// do sth
		setURLImage();

		WordFactory.getInstance(this); // 初始化数据库
		// 如果用户单词表words_log是空的，并且存在临时文件temp，则用temp中的数据恢复表words_log
		if (WordFactory.getInstance(this).getStudyWordCount() == 0 && new File(this.getFilesDir(), "temp").exists()) {
			MobclickAgentData.exception(this, "in WelcomeActivity doSomething(): 恢复用户数据");
			WordFactory.getInstance(this).importTableWordsLog();
		}

		LocationAndSchoolFactory.getInstance(this);

		// 测试用，发布时需注释
		// WordFactory.getInstance(this).updateWordForTest();

		/*
		 * if (!WordFactory.getInstance(this).tabbleIsExist(
		 * WordFactory.TABLE_WORDS)) {
		 * //Log.e("db version",WordFactory.getInstance(this).getVersion()+"");
		 * copyDB(this);
		 * //Log.e("db version",WordFactory.getInstance(this).getVersion()+"");
		 * WordFactory.getInstance(this).createIndexs();
		 * WordFactory.getInstance(this).importTableWordsLog(); //初始化数据库，执行升级 }
		 */

		// 为了修复错发的1.1.4版中没有执行DatabaseHelper中的updateDatabaseVersion2to3()的bug，此处加一个补丁
		// WordFactory.getInstance(this).updateWithoutTimeLockInWords();

		// 解压缩raw目录的音频压缩包
		if (!FileManager.isZipFileExist(FileManager.IN_OLD_VOICE_SUFFIX_NAME))
			unzipRawVoiceFile(WelcomeActivity.this);

		if (!AppPreference.hasSetStudyNotification(this))
			AppPreference.setStudyNotification(this, true);
		if (!AppPreference.hasSetSprintMode(this))
			AppPreference.setSprintMode(this, false);

		// LogUtil.addLog("启动");

		if (AppPreference.hasStudyingBook(WelcomeActivity.this)) {
			toSync(WelcomeActivity.this);

			DataManager.getInstance().doStudyProgress(WelcomeActivity.this);
			// DataManager.getInstance().init(WelcomeActivity.this);
		}

		// 初始化经验值
		if (AppPreference.getEXP(WelcomeActivity.this) == -1)
			DataManager.getInstance().initExp(WelcomeActivity.this);

		int count = WordFactory.getInstance(WelcomeActivity.this).getUnFamiliarWordCount() + WordFactory.getInstance(WelcomeActivity.this).getFamiliarWordCount()
				+ WordFactory.getInstance(WelcomeActivity.this).getTooEasyWordCount();

		new Thread() {
			public void run() {
				movePhraseFile();
			};
		}.start();

		long end = System.currentTimeMillis();
		Log.e("inittime", end - start + ",words count:" + count);
		// LogUtil.addLog1("inittime:" + (end - start) + ",words count:" +
		// count);
		return end - start;
	}

	/**
	 * 拆分单词书
	 */
	private void splitBook() {
		if (AppPreference.getBook(this) != -1 && AppPreference.getWordBookIndex(this) == -1 && AppPreference.getPhraseBookIndex(this) == -1) { // 说明还没有拆分
			LogUtil.d("开始拆分单词书");
			int bookIndex = AppPreference.getBook(this);
			int year = AppPreference.getPlanEndYear(this);
			int month = AppPreference.getPlanEndMonth(this);
			int day = AppPreference.getPlanEndDay(this);
			int planStartDate = AppPreference.getPlanStartDate(this);
			DataManager.getInstance().resetStudyPlan(this, bookIndex, year, month, day, planStartDate);
			LogUtil.d("拆分单词书结束");
		}
	}

	/**
	 * 将phrase文件夹里的音频移动到phrase_wg
	 */
	private void movePhraseFile() {
		LogUtil.d("调用movePhraseFile()");
		FileManager.movePhraseFile();
	}

	Handler syncHandler = new Handler() {

		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {
			case UserInterface.MSG_START:
				// dialog2 = ProgressDialog.show(context, null, "正在同步用户数据...");
				break;
			case UserInterface.MSG_SUCCESS:
				// Toast.makeText(WelcomeActivity.this, "启动时同步用户数据成功",
				// Toast.LENGTH_SHORT).show();
				// 修改自动同步日期
				AppPreference.setAutoSyncDateAfterStartup(WelcomeActivity.this, DateTimeUtils.getDate());
				break;
			case UserInterface.MSG_UNSUCCESS:
				// Toast.makeText(WelcomeActivity.this, "同步失败",
				// Toast.LENGTH_SHORT).show();
				break;
			case UserInterface.MSG_BAD_NETWORK:
				// Toast.makeText(WelcomeActivity.this, "同步失败,请确认网络是否连接",
				// Toast.LENGTH_SHORT).show();
				break;
			case UserInterface.MSG_WEB_SITE_ACCESS_FAILURE:
				// Toast.makeText(WelcomeActivity.this, "同步失败,无法访问网站，请确认网络是否连接",
				// Toast.LENGTH_SHORT).show();
				break;
			default:
				break;
			}
		};
	};

	// 每天第一次启动，同步用户数据
	protected void toSync(Context context) {
		int today = DateTimeUtils.getDate();
		int autoSYncDateAfterStartup = AppPreference.getAutoSyncDateAfterStartup(context);

		if (UserInterface.getInstance(WelcomeActivity.this).isLogin() && autoSYncDateAfterStartup != today) {
			syncHandler.sendMessage(syncHandler.obtainMessage(UserInterface.MSG_START));
			UserInterface.getInstance(context).sync(syncHandler);
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onPause(this);

		// 启动锁屏服务
		LockService.startActivity(WelcomeActivity.this);
	}

	// private void setImageTemp() {
	// int todayDate = DateTimeUtils.getDate();
	//
	// if (todayDate >= 20141222 && todayDate <= 20141225) {
	// findViewById(R.id.welcome_loading).setVisibility(View.GONE);
	// findViewById(R.id.welcome_bg).setBackgroundResource(R.drawable.welcome_bg_christmas);
	// } else if (todayDate >= 20141226 && todayDate <= 20150104) {
	// findViewById(R.id.welcome_loading).setVisibility(View.GONE);
	// findViewById(R.id.welcome_bg).setBackgroundResource(R.drawable.welcome_bg_new_year);
	// }
	// }

	/*
	 * 设置启动时候的网络广告图片 图片显示规则是： 1、软件每天第一次打开会清空所有原来的本地图片资源。
	 * 2、软件只有每天第一次打开会100%去请求最高优先级的那张图片，本日其他时候则不会再去请求这张图片。
	 * 3、如果软件第一次打开找到了最高优先级图片，则显示最高优先级图片，如果请求不到则会随机请求另外的3张图片中的1张。
	 * 4、软件本日非第一次打开时候如果本地有最高优先级图片存在则直接显示最高优先级图片，若不存在则随机请求3张中的1张。
	 * 5、在请求网络上的3张图片之前先检查本地是否存在，若不存在才请求网络上图片。
	 */

	private void setURLImage() {
		int todayDate = DateTimeUtils.getDate();
		int dateOld = AppPreference.getIsFirstOpenThisDay(WelcomeActivity.this);
		if (todayDate != dateOld) {
			// 清空已下载的图片
			AppPreference.setADs1(WelcomeActivity.this, null);
			AppPreference.setADs2(WelcomeActivity.this, null);
			AppPreference.setADs3(WelcomeActivity.this, null);
			AppPreference.setADSPriority(WelcomeActivity.this, null);
			getImagesPro();
			AppPreference.setIsFirstOpenThisDay(WelcomeActivity.this, todayDate);
		} else {
			String imageURL = AppPreference.getADSPriority(WelcomeActivity.this);
			if (imageURL != null) {
				setADs(Uri.parse(imageURL));
			} else {
				getImages();
			}
		}
	}

	private void getImages() {
		int randomAD = (int) (Math.random() * 3);
		String imageURL;
		switch (randomAD) {
		case 0:
			imageURL = AppPreference.getADs1(WelcomeActivity.this);
			if (imageURL != null)
				setADs(Uri.parse(imageURL));
			else
				getBitmapFromUrl(dynamicImageURL1 + "ad1.jpg", Utils.welcomeADsIndex.ad1);
			break;
		case 1:
			imageURL = AppPreference.getADs2(WelcomeActivity.this);
			if (imageURL != null)
				setADs(Uri.parse(imageURL));
			else
				getBitmapFromUrl(dynamicImageURL1 + "ad2.jpg", Utils.welcomeADsIndex.ad2);
			break;
		case 2:
			imageURL = AppPreference.getADs3(WelcomeActivity.this);
			if (imageURL != null)
				setADs(Uri.parse(imageURL));
			else
				getBitmapFromUrl(dynamicImageURL1 + "ad3.jpg", Utils.welcomeADsIndex.ad3);
			break;
		}
	}

	private void getImagesPro() {
		getBitmapFromUrl(dynamicImageURL1 + "ad_priority.jpg", Utils.welcomeADsIndex.adPro);
	}

	private void setADs(Bitmap bt) {
		if (!hasSetAd) {
			synchronized (WelcomeActivity.this) {
				if (!hasSetAd) {
					hasSetAd = true;
					// findViewById(R.id.ad_views).setBackgroundDrawable(new
					// BitmapDrawable(bt));
					((ImageView) findViewById(R.id.ad_views)).setImageBitmap(bt);
					Animation fadeIn = AnimationUtils.loadAnimation(WelcomeActivity.this, R.anim.fade_in);
					findViewById(R.id.ad_views).startAnimation(fadeIn);
				}
			}
		}
	}

	private void setADs(Uri imageUri) {
		Bitmap bt = null;
		try {
			bt = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		mHandler.obtainMessage(SET_ADS, bt).sendToTarget();
	}

	private void getBitmapFromUrl(final String imgUrl, final Utils.welcomeADsIndex index) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				URL url;
				Bitmap bitmap = null;
				try {
					url = new URL(imgUrl);
					InputStream is = url.openConnection().getInputStream();
					BufferedInputStream bis = new BufferedInputStream(is);
					bitmap = BitmapFactory.decodeStream(bis);
					bis.close();
					mHandler.obtainMessage(SET_ADS, bitmap).sendToTarget();
					BitmapUtil.saveADs(bitmap, index, WelcomeActivity.this);
				} catch (Exception e) {
					e.printStackTrace();
					bitmap = null;
					mHandler.obtainMessage(GET_AD_FAILED).sendToTarget();
				}
			}
		}).start();
	}

	public void unzipRawVoiceFile(final Context context) {
		Thread a = new Thread(new Runnable() {
			public void run() {
				File file = new File(FileManager.getZipFilePath(FileManager.IN_OLD_VOICE_SUFFIX_NAME) + ".nc");
				try {
					FileOutputStream os = new FileOutputStream(file);
					InputStream in = context.getResources().openRawResource(R.raw.audio_absent_in_old);
					byte[] buffer = new byte[4096];
					while (in.available() > 0) {
						int i = in.read(buffer);
						if (i > 0)
							os.write(buffer, 0, i);
						os.flush();
					}
					in.close();
					os.close();
					String downloadedVoiceFilePath = FileManager.renameDownloadCompelateFile(file);
					FileManager.unZipDownloadedVoiceFile(new File(downloadedVoiceFilePath));
				} catch (ZipException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		a.start();
	}

}
